package com.fen.testdemo.async;

import java.io.IOException;
import java.util.concurrent.CompletableFuture;

public class Main {
    public static void main(String[] args) throws Exception {

        HttpTask task = new HttpTask();

        System.out.println("main threadstarts in thread id: "+Thread.currentThread().getId());

        CompletableFuture<String> futureNonBlocking =CompletableFuture.supplyAsync(()-> {
            try {
                return task.doHttp("https://guazi.com");
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
            return "error";
        });
        CompletableFuture futureBlocking= CompletableFuture.supplyAsync(() -> {
            try {
                return task.doHttp("https://baidu.com");
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
            return "errors";
        });

        // 非阻塞
        System.out.println("-----------------非阻塞位1----------------------\n");
        // future.thenAcceptAsync() 方法阻塞本线程，http请求成功后执行回调函数
        futureNonBlocking.thenAcceptAsync(result -> System.out.println("\nfrom non blocking future:\n+result+\n"));
        System.out.println("-----------------非阻塞位2----------------------\n");

        // 阻塞
        System.out.println("\nfromblocking future:\n+futureBlocking.get()+\n");
//         future.get() //方法阻塞本线程，直http请求成功
        System.out.println("-----------------阻塞位1----------------------\n");
        System.out.println("main threadends");
    }
}